package com.javacoo.xservice.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.javacoo.xservice.base.config.Resources;
import com.javacoo.xservice.base.exception.BaseException;
import com.javacoo.xservice.base.exception.BusinessException;
import com.javacoo.xservice.base.exception.IllegalParameterException;
import com.javacoo.xservice.base.exception.NotSupportedHttpMediaTypeException;
import com.javacoo.xservice.base.support.swaparea.SwapAreaUtils;
import com.javacoo.xservice.base.utils.FastJsonUtil;
import com.javacoo.xservice.base.utils.WebUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 统一异常处理
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2017年7月25日下午2:00:32
 */
@Slf4j
@ControllerAdvice
public class ExcepitonController extends BaseController{

	/**
	 * 统一异常处理
	 * <p>说明:</p>
	 * <li></li>
	 * @author DuanYong
	 * @param request
	 * @param response
	 * @param ex
	 * @throws Exception
	 * @since 2017年6月30日下午2:43:57
	 */
	@ExceptionHandler(Exception.class)
	protected final void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
			throws Exception {
		ex.printStackTrace();
		BaseRequest baseRequest = WebUtil.getBaseRequest(request);
		String transSn = StringUtils.isBlank(WebUtil.getSwapAreaData().getTransactionSn())?WebUtil.genTransSn():WebUtil.getSwapAreaData().getTransactionSn();
		if(null != baseRequest){
			transSn = baseRequest.getTransactionSn();
		}
		log.error(Resources.getMessage(ErrorCodeConstants.COMMON_EXCEPTION_HEAD), transSn,ex);
		BaseResponse resp = new BaseResponse();
		resp.setTransactionSn(transSn);
		if (ex instanceof BaseException) {
			((BaseException) ex).handler(resp);
		} else if (ex instanceof IllegalArgumentException) {
			new IllegalParameterException(ex.getMessage()).handler(resp);
		} else if (ex instanceof BusinessException) {
			new BusinessException(ex.getMessage()).handler(resp);
		} else if (ex instanceof HttpMediaTypeNotSupportedException) {
			new NotSupportedHttpMediaTypeException(ex.getMessage()).handler(resp);
		} else if (ex instanceof HttpMessageNotReadableException) {
			new IllegalParameterException(ex.getMessage()).handler(resp);
		}else if (ex instanceof RuntimeException) {
			new IllegalParameterException(ex.getMessage()).handler(resp);
		} else {
			new IllegalParameterException().handler(resp);
		}
        //设置响应数据
        SwapAreaUtils.getSwapAreaData().setEndTime(System.currentTimeMillis());
        SwapAreaUtils.getSwapAreaData().setBaseResponse(resp);
		response.setContentType(Constants.JSON_CONTENT_TYPE);
		response.getWriter().write(FastJsonUtil.toJSONString(resp));
	}
}
